package com.wlw.admin.openeye.ui.fragment

import android.graphics.Rect
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.wlw.admin.openeye.R
import com.wlw.admin.openeye.base.BaseFragment
import com.wlw.admin.openeye.mvp.contract.CategoryContract
import com.wlw.admin.openeye.mvp.model.bean.CategoryBean
import com.wlw.admin.openeye.mvp.presenter.CategoryPresenter
import com.wlw.admin.openeye.net.exception.ErrorStatus
import com.wlw.admin.openeye.showToast
import com.wlw.admin.openeye.ui.adapter.CategoryAdapter
import com.wlw.admin.openeye.utils.DisplayManager
import kotlinx.android.synthetic.main.layout_recyclerview.*

class CategoryFragment : BaseFragment(), CategoryContract.View {

    private val mPresenter by lazy {
        CategoryPresenter()
    }
    private val mAdapter by lazy {
        context?.let { CategoryAdapter(it, mCategoryList) }
    }
    private var mCategoryList = ArrayList<CategoryBean>()

    companion object {
        fun getInstance() = CategoryFragment()
    }

    override fun getLayoutId(): Int = R.layout.layout_recyclerview


    override fun lazyLoad() {
        mPresenter.getCategoryData()
    }

    override fun initView() {
        mPresenter.attachView(this)
        mLayoutStatusView = multipleStatusView
        mRecyclerView.adapter = mAdapter
        mRecyclerView.layoutManager = activity?.let { GridLayoutManager(it, 2) }
        mRecyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                val posi = parent.getChildLayoutPosition(view)
                val offset = DisplayManager.dip2px(2f)
                offset?.let { outRect.set(if (posi % 2 == 0) 0 else offset, it, if (posi % 2 == 0) offset else 0, offset) }
            }
        })
    }

    override fun showCategory(categoryList: ArrayList<CategoryBean>) {
        mCategoryList = categoryList
        mAdapter?.setData(mCategoryList)
    }

    override fun showError(errorMsg: String, errorCode: Int) {
        showToast(errorMsg)
        if (errorCode == ErrorStatus.NETWORK_ERROR)
            mLayoutStatusView?.showNoNetwork()
        else
            mLayoutStatusView?.showError()
    }

    override fun showLoading() {
        mLayoutStatusView?.showLoading()
    }

    override fun dismissLoading() {
        mLayoutStatusView?.showContent()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.detachView()
    }
}